package com.jyu.apts.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.jyu.apts.dto.ResultDto;
import com.jyu.apts.dto.TableDto;
import com.jyu.apts.dto.UserDto;
import com.jyu.apts.entity.Organization;
import com.jyu.apts.entity.OrganizationRole;
import com.jyu.apts.entity.Role;
import com.jyu.apts.entity.User;
import com.jyu.apts.entityEnum.UserStatusTypeEnum;
import com.jyu.apts.service.OrganizationRoleService;
import com.jyu.apts.service.OrganizationService;
import com.jyu.apts.service.RoleService;
import com.jyu.apts.service.UserService;
import com.jyu.apts.utils.PasswordEntryUtil;

@RestController
public class OrganizationUserController {

	final static String ORGANIZATIONUSERROLE = "organizationUser";
	@Autowired
	UserService userService;
	@Autowired
	RoleService roleService;
	@Autowired
	OrganizationService organizationService;
	@Autowired
	OrganizationRoleService organizationRoleService;
	
	@RequiresPermissions("organizationUser_html")
	@RequestMapping("/addOrganizationUser")
	public ResultDto addUser(String username,String password,long organizationRoleId,String nickname) {
		if(userService.findByUsername(username)!=null)
			return new ResultDto("添加失败!用户名已存在!",null,2);
		UserDto userDto = (UserDto) SecurityUtils.getSubject().getSession().getAttribute("userDto");
		User orgAdmin = userService.getOne(userDto.getId());
		Organization organization = orgAdmin.getOrganization();
		User user = new User();
		user.setNickname(nickname);
		user.setOrganization(organization);
		Role role = roleService.findByStringRole(ORGANIZATIONUSERROLE);
		user.setRole(role);
		user.setPassword(password);
		user.setUsername(username);
		OrganizationRole organizationRole = organizationRoleService.getOne(organizationRoleId);
		if(organizationRole == null) {
			return new ResultDto("角色不存在",null,2);
		}
		if(organizationRole.getOrganization().getId()!=organization.getId()) {
			return new ResultDto("非本机构角色",null,2);
		}
		user.setOrganizationRole(organizationRole);
		if(user.getPassword()==null || user.getPassword().trim().length()==0)
			user.setPassword("123456");
		user.setStatus(UserStatusTypeEnum.Active.getType());
		user = PasswordEntryUtil.encrypt(user);
		userService.save(user);
		return new ResultDto("添加成功",null,0);
	}
	
	@RequiresPermissions("organizationUser_html")
	@RequestMapping("/upOrganizationUser")
	public ResultDto upUser(long id,String nickname,String password,String phone,String username,Integer status,long organizationRoleId) {
		User db_user = userService.getOne(id);
		if(db_user == null)
			return new ResultDto("用户不存在",null,2);
		UserDto userDto = (UserDto) SecurityUtils.getSubject().getSession().getAttribute("userDto");
		User orgAdmin = userService.getOne(userDto.getId());
		if(db_user.getOrganization().getId()!=orgAdmin.getOrganization().getId())
			return new ResultDto("非本机构人员",null,2);
		db_user.setStatus(status);
		if(!db_user.getUsername().equals(username) && userService.findByUsername(username)!=null)
			return new ResultDto("修改失败!用户名已被注册!",null,2);
		db_user.setUsername(username);
		db_user.setNickname(nickname);
		if(password!=null && password.trim().length()!=0) {
			db_user.setPassword(password);
			db_user = PasswordEntryUtil.encrypt(db_user);
		}
		userService.save(db_user);
		OrganizationRole organizationRole = organizationRoleService.getOne(organizationRoleId);
		if(organizationRole == null) {
			return new ResultDto("角色不存在",null,2);
		}
		if(organizationRole.getOrganization().getId()!=db_user.getOrganization().getId()) {
			return new ResultDto("非本机构角色",null,2);
		}
		db_user.setOrganizationRole(organizationRole);
		return new ResultDto("更新成功",null,0);
	}
	
	@RequiresPermissions("organizationUser_html")
	@RequestMapping("/delOrganizationUser")
	public ResultDto delUser(String ids) {
		String[] idArray = ids.split(",");
		List<Long> l_ids = new ArrayList<Long>();
		for(String id : idArray) {
			l_ids.add(new Long(id));
		}
		UserDto userDto = (UserDto) SecurityUtils.getSubject().getSession().getAttribute("userDto");
		User orgAdmin = userService.getOne(userDto.getId());
		Organization organization = orgAdmin.getOrganization();
		List<User> users = userService.findAllById(l_ids);
		for(User user : users){
			if(user.getOrganization().getId()!=organization.getId()) {
				return new ResultDto("存在非本机构人员",null,2);
			}
		};
		userService.delete(users);
		return new ResultDto("删除成功",null,0);
	}
	
	@RequiresPermissions("organizationUser_html")
	@RequestMapping("/getOrganizationUserPage")
	public TableDto<UserDto> getUserPage(Integer pageNumber,Integer pageSize,String search) {
		UserDto userDto = (UserDto) SecurityUtils.getSubject().getSession().getAttribute("userDto");
		User orgAdmin = userService.getOne(userDto.getId());
		Role role = roleService.findByStringRole(ORGANIZATIONUSERROLE);
		Page<User> pageResult = userService.getUserPage(pageNumber, pageSize, role.getId(), orgAdmin.getOrganization().getId(), search);
		List<User> users = pageResult.getContent();
		List<UserDto> userDtos = new ArrayList<UserDto>();
		users.forEach(user->userDtos.add(new UserDto().convert(user)));
		return new TableDto<UserDto>(userDtos,pageResult.getTotalElements());
	}
	
	@RequiresPermissions("organizationUser_html")
	@RequestMapping("/organizationUser_html")
	public ModelAndView organizationUser_html() {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/organizationUser.html");
		return mv;
	}
}
